<template>
	<l-page class="page-card" :page.sync="queryParams.pageNum" :page-size.sync="queryParams.pageSize" :total="total" @getList="getList">
		<el-form ref="queryForm" slot="header" :inline="true" :model="queryParams" label-width="75px" label-position="left">
			<el-form-item label="资讯分类:" prop="classify">
				<el-select v-model="queryParams.classify" placeholder="请选择分类">
					<el-option :value="null" label="全部" />
					<el-option v-for="(value, index) in cateList" :key="index" :label="value.dictLabel" :value="value.dictValue" />
				</el-select>
			</el-form-item>
			<el-form-item label="资讯标题:" prop="title">
				<el-input v-model.trim="queryParams.title" clearable placeholder="请输入标题" />
			</el-form-item>
			<el-form-item label="资讯状态:" prop="state">
				<el-select v-model="queryParams.state" placeholder="请选择状态">
					<el-option :value="null" label="全部" />
					<el-option label="上架" value="0" />
					<el-option label="下架" value="1" />
				</el-select>
			</el-form-item>
			<start-end-time ref="child" :get-time="getTime" title="创建时间:"></start-end-time>
		</el-form>
		<template slot="options">
			<l-search @search="handleQuery" @refresh="resetQuery" />
			<el-button v-hasPermi="['system:consult:add']" type="primary" icon="el-icon-plus" @click="handleAdd">新增资讯 </el-button>
			<el-button v-hasPermi="['system:consult:add']" type="primary" icon="el-icon-plus" @click="handleAddCategory">新增分类 </el-button>
		</template>
		<el-table v-loading="loading" :data="consultList" stripe @sort-change="handleSortChange" @selection-change="handleSelectionChange">
			<el-table-column :formatter="emptyToString" align="center" label="序号" type="index" width="50" />
			<el-table-column :formatter="emptyToString" align="center" label="分类" prop="classify" min-width="156" />
			<el-table-column :formatter="emptyToString" align="center" label="标题" min-width="156" prop="title" show-overflow-tooltip> </el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="内容" min-width="200" prop="context" show-overflow-tooltip>
				<template slot-scope="scope">
					<div class="multi-one" v-html="scope.row.context"></div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="图片" width="160">
				<template slot-scope="scope">
					<el-image v-if="scope.row.picUrl" :preview-src-list="[scope.row.picUrl.split(',')[0]]" :src="scope.row.picUrl.split(',')[0]" style="width: 48px; height: 48px"> </el-image>
					<div v-else>-</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToNumber" align="center" label="点赞数量" min-width="120" prop="likesCount" sortable> </el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="状态" min-width="120">
				<template slot-scope="scope">
					<el-switch v-model.trim="scope.row.state" :active-value="0" :inactive-value="1" active-text="上架" class="switch" inactive-text="下架" @change="handleUpdateStatus(scope.row)"></el-switch>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" align="center" label="创建时间" min-width="156" prop="createTime">
				<template slot-scope="scope">
					<div class="w-full flex flex-col items-center">
						<span>{{ dayjs(scope.row.createTime).format('YYYY-MM-DD') }}</span>
						<span>{{ dayjs(scope.row.createTime).format('HH:mm:ss') }}</span>
					</div>
				</template>
			</el-table-column>
			<el-table-column :formatter="emptyToString" :width="tableAction" align="center" fixed="right" header-align="center" label="操作">
				<template slot-scope="scope">
					<div class="table-action">
						<el-button v-hasPermi="['system:consult:edit']" type="primary" @click="handleUpdate(scope.row)">编辑 </el-button>
						<el-button v-hasPermi="['system:consult:remove']" type="danger" @click="handleDelete(scope.row, scope)">删除 </el-button>
					</div>
				</template>
			</el-table-column>
		</el-table>
		<l-dialog v-model="dialogVisible" title="新增分类" width="500px" @close="handleClose" @formClose="handleClose" @formSubmit="addCategory">
			<el-form label-width="120px">
				<el-form-item label="新增分类名称:">
					<el-input v-model.trim="cateName" autocomplete="off" maxlength="5" show-word-limit></el-input>
				</el-form-item>
				<el-form-item label="已有分类名称:">
					<div class="flex flex-wrap">
						<div v-for="(tag, index) in cateList" :key="index" class="relative w-[88px] h-[40px] bg-[#F7F7F7] rounded-[4px] mr-[16px] text-center cursor-pointer mb-[10px]">
							{{ tag.dictLabel }}
							<div class="absolute top-0 right-0 bg-red rounded-[50%] text-white h-[14px] w-[14px] flex items-center justify-center cursor-pointer" @click="handleCloseTag(tag, index)">
								<i class="el-icon-close"></i>
							</div>
						</div>
					</div>
				</el-form-item>
			</el-form>
		</l-dialog>
		<l-dialog v-model="showContext" :show-button="false" title="查看" width="500px" @close="showContext = false">
			<div class="html-box" v-html="htmlContent"></div>
		</l-dialog>
	</l-page>
</template>

<script>
import { delConsult, exportConsult, listConsult, updateConsult } from '@/api/mall/consult';
import { addData, delData } from '@/api/system/dict/data';
import StartEndTime from '@/components/StartEndTime';
import debounce from 'lodash/debounce';
import tableMixins from '@/mixins/table';
import TemplateZone from '@/views/mall/logistics/templateZone';
export default {
	name: 'Consult',
	components: { TemplateZone, StartEndTime },
	mixins: [tableMixins],
	beforeRouteEnter(to, from, next) {
		next((vm) => {
			if (from.path === '/shop/consultCreate') {
				vm.getList();
			}
			// 通过 `vm` 访问组件实例
		});
	},
	data() {
		return {
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 资讯管理表格数据
			consultList: [],
			// 弹出层标题
			title: '',
			// 是否显示弹出层
			open: false,
			// 搜索参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				classify: null,
				title: null,
				state: null,
				startTime: null,
				endTime: null,
				sortDesc: null,
				sortStr: null,
			},
			// 表单参数
			form: {},
			formLoading: false,
			// 表单校验
			rules: {},
			dialogVisible: false,
			cateName: '',
			cateList: [],
			htmlContent: '',
			showContext: false,
		};
	},
	created() {
		this.getList();
		this.getCategory();
	},
	methods: {
		handleExamine(row) {
			this.htmlContent = row.context;
			this.showContext = true;
		},
		getCategory() {
			this.getDicts('sys_concult_type').then((res) => {
				this.cateList = res.data;
			});
		},
		addCategory: debounce(
			function () {
				if (!this.cateName) {
					this.$message.error('请输入分类名称!');
					return;
				}
				addData({
					dictLabel: this.cateName,
					dictValue: this.cateName,
					dictSort: 1,
					status: '0',
					dictType: 'sys_concult_type',
				}).then(() => {
					this.$message.success('新增分类成功!');
					this.handleClose();
					this.getCategory();
				});
			},
			1500,
			{
				leading: true,
				trailing: false,
			}
		),
		handleCloseTag(tag, index) {
			console.log(tag);
			this.$confirm('确定删除该分类名称吗?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(() => {
					delData(tag.dictCode).then(() => {
						this.cateList.splice(index, 1);
						this.getCategory();
					});
					this.$message({
						type: 'success',
						message: '删除成功!',
					});
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除',
					});
				});
		},
		handleClose() {
			this.dialogVisible = false;
			this.cateName = '';
		},
		handleAddCategory() {
			this.dialogVisible = true;
		},
		handleUpdateStatus(row) {
			updateConsult({ id: row.id, state: row.state })
				.then(() => {
					this.$message.success(row.state ? '下架成功' : '上架成功');
					this.getList();
				})
				.catch(() => {
					row.status = !row.status;
				});
		},
		/** 搜索资讯管理列表 */
		getList() {
			this.loading = true;
			if (this.queryParams.time) {
				this.queryParams.startTime = this.queryParams.time[0];
				this.queryParams.endTime = this.queryParams.time[1];
			}
			listConsult(this.queryParams).then((response) => {
				this.consultList = response.data.records;
				this.total = response.data.total;
				this.loading = false;
				this.setActionWidth();
			});
		},
		// 取消按钮
		cancel() {
			this.open = false;
			this.reset();
		},
		// 表单重置
		reset() {
			this.form = {
				id: null,
				consultSn: null,
				classify: null,
				title: null,
				state: null,
				visits: null,
				commentsNumber: null,
				author: null,
				userId: null,
				delFlag: null,
				createBy: null,
				createTime: null,
				updateBy: null,
				updateTime: null,
				tenantId: null,
				sortDesc: null,
				sortStr: null,
			};
			this.resetForm('form');
		},
		getTime(startTime, endTime) {
			this.queryParams.startTime = startTime;
			this.queryParams.endTime = endTime;
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1;
			this.getList();
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.$refs.child.resetTime();
			this.resetForm('queryForm');
			this.handleQuery();
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map((item) => item.id);
			this.single = selection.length !== 1;
			this.multiple = !selection.length;
		},
		/** 新增按钮操作 */
		handleAdd() {
			this.$router.push('consultCreate');
		},
		/** 编辑按钮操作 */
		handleUpdate(row) {
			let id = row.id;
			this.$router.push('consultCreate?id=' + id);
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			const ids = row.id || this.ids;
			this.$dialogRemove('确定删除该资讯吗？').then((res) => {
				delConsult({ id: [ids] }).then(() => {
					this.$message({
						type: 'success',
						message: '删除成功!',
					});
					setTimeout(() => {
						this.getList();
						res.hide();
						res.loading(false);
					}, 100);
				});
			});
		},
		/** 导出按钮操作 */
		handleExport() {
			const queryParams = this.queryParams;
			this.$confirm('是否确认导出所有资讯管理数据项?', '警告', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
			})
				.then(function () {
					return exportConsult(queryParams);
				})
				.then((response) => {
					this.download(response.msg);
				});
		},
	},
};
</script>
<style lang="scss" scoped>
::v-deep img {
	width: 100%;
}

.html-box {
	padding: 5px;

	border-radius: 10px;
}

::v-deep.pagination-container {
	background: none;
}
</style>
